<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>数据库调优理论 | 王开琦的个人小站</title><meta name="author" content="王开琦"><meta name="copyright" content="王开琦"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="索引的数据结构B-Tree二叉搜索树:   平衡二叉搜索树（AVL树）:  在普通的二叉搜索树上增加了约束，上图中的第一个二叉树就满足AVL的定义：  每个节点的左子树和右子树的高度差不超过1 对于n个节点，树的深度是 log2n，查询的时间复杂度是 O(log2n)  假设 n 非常的大，那么树的深度依然会非常高，查询次数也会很多。 在 n 一定的情况下，增加树的分叉，就会减少树的深度，这种情况">
<meta property="og:type" content="article">
<meta property="og:title" content="数据库调优理论">
<meta property="og:url" content="https://blog.wkq.pub/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/index.html">
<meta property="og:site_name" content="王开琦的个人小站">
<meta property="og:description" content="索引的数据结构B-Tree二叉搜索树:   平衡二叉搜索树（AVL树）:  在普通的二叉搜索树上增加了约束，上图中的第一个二叉树就满足AVL的定义：  每个节点的左子树和右子树的高度差不超过1 对于n个节点，树的深度是 log2n，查询的时间复杂度是 O(log2n)  假设 n 非常的大，那么树的深度依然会非常高，查询次数也会很多。 在 n 一定的情况下，增加树的分叉，就会减少树的深度，这种情况">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://blog.wkq.pub/media/top_img.jpg">
<meta property="article:published_time" content="2022-04-22T08:13:31.000Z">
<meta property="article:modified_time" content="2022-04-23T14:57:20.088Z">
<meta property="article:author" content="王开琦">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://blog.wkq.pub/media/top_img.jpg"><link rel="shortcut icon" href="/media/favicon.ico"><link rel="canonical" href="https://blog.wkq.pub/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '数据库调优理论',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-04-23 22:57:20'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><meta name="generator" content="Hexo 5.2.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/media/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">15</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">17</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/media/top_img.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">王开琦的个人小站</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">数据库调优理论</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-04-22T08:13:31.000Z" title="发表于 2022-04-22 16:13:31">2022-04-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-04-23T14:57:20.088Z" title="更新于 2022-04-23 22:57:20">2022-04-23</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/">数据库</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98/">数据库监控与调优</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>11分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="索引的数据结构"><a href="#索引的数据结构" class="headerlink" title="索引的数据结构"></a>索引的数据结构</h2><h3 id="B-Tree"><a href="#B-Tree" class="headerlink" title="B-Tree"></a>B-Tree</h3><div class="note primary simple"><p>二叉搜索树:</p>
</div>
<p><img src= "" data-lazy-src="二叉树查找.png" alt=""></p>
<div class="note primary simple"><p>平衡二叉搜索树（AVL树）:</p>
</div>
<p>在普通的二叉搜索树上增加了约束，上图中的第一个二叉树就满足AVL的定义：</p>
<ul>
<li>每个节点的左子树和右子树的高度差不超过1</li>
<li>对于n个节点，树的深度是 log2n，查询的时间复杂度是 O(log2n)</li>
</ul>
<p>假设 n 非常的大，那么树的深度依然会非常高，查询次数也会很多。</p>
<p>在 n 一定的情况下，增加树的分叉，就会减少树的深度，这种情况下，需要定位某一个节点的时候，查询的次数也减少了。</p>
<div class="note primary simple"><p>平衡多路搜索树（B-Tree，Balance Tree）:</p>
</div>
<p>通过 B-Tree 可以有效的把树的高度降下来，树的阶越大，树的高度就越低，查询的次数也就越少</p>
<p><img src= "" data-lazy-src="平衡多路搜索树.png" alt="三阶B-Tree"></p>
<ul>
<li>阶是 B-Tree的一个参数，阶越大表示一个节点允许拥有的孩子越多 </li>
<li>根节点的子节点个数 2 &lt;=x &lt;= m ，m是树的阶<ul>
<li>假设 m=3，则根节点可以有 2-3个孩子</li>
</ul>
</li>
<li>中间节点的子节点个数 m/2 &lt;= y &lt;=m<ul>
<li>假设 m=3，中间节点至少有 2  个孩子，最多 3 个孩子</li>
</ul>
</li>
<li>每个中间节点包含 n 个关键字，n = 子节点个数-1，且按升序排序<ul>
<li>如果中间节点有3个子节点，则里面会有两个关键字，且按升序排序</li>
</ul>
</li>
<li>Pi(i=1,n+1)为指向子树根节点的指针。其中P[1]指向关键字小于Key[1]的子树，P[i]指向关键字属于（Key[i-1],Key[i]）的子树，P[n+1]指向关键字大于Key[n]的子树<ul>
<li>P1、P2、P3为指向子树根节点的指针，P1指向关键字小于Key1的树；P2指向key1-key2之间的子树；P3指向大于 key2 的树</li>
</ul>
</li>
</ul>
<div class="note primary simple"><p>B+Tree:</p>
</div>
<ul>
<li>B+Tree 是在 B-Tree 基础上的一种优化</li>
<li>InnoDB 存储引擎使用B+Tree实现其索引结 构</li>
</ul>
<p><img src= "" data-lazy-src="B+Tree.png" alt=""></p>
<p>B-Tree 和 B+ Tree 的差异</p>
<ul>
<li>B+Tree 有n个子节点的节点中含有 n 个关键字<ul>
<li>B-Tree 是 n 个子节点的节点有 n-1 个关键字</li>
</ul>
</li>
<li>B+Tree中，所有的叶子节点包含了全部关键字的信息，且叶子节点按照关键字的大小自小到大顺序链接，构成一个有序链表<ul>
<li>B-Tree 的叶子节点不包括全部关键字</li>
</ul>
</li>
<li>B+Tree中，非叶子节点仅用于索引，不保存数据，记录存放在叶子节点中<ul>
<li>B-Tree中，非叶子节点既保存索引，也保存数据</li>
</ul>
</li>
</ul>
<p>由于B+Tree的中间节点，它只用来做索引，于是相同的空间B+Tree非叶子节点能够存储的数据更多，B+Tree 更加的矮，磁盘IO的次数也会更少。</p>
<p>由于B-Tree 的中间节点也存储数据，所以它的查询效率不是很稳定。最好的情况在根节点，最差的情况是在叶子节点。</p>
<p>B+Tree 对范围查询、排序的性能要比B-Tree 好</p>
<hr>
<p>B+Tree   ： 聚簇索引</p>
<ul>
<li>主键索引：叶子节点存储主键及数据</li>
<li>非主键索引（二级索引、辅助索引）：叶子节点存储索引及主键</li>
</ul>
<p>B+Tree   ： 非聚簇索引</p>
<ul>
<li>主键/非主键索引的叶子节点都是存储指向数据块的指针</li>
</ul>
<h3 id="Hash索引"><a href="#Hash索引" class="headerlink" title="Hash索引"></a>Hash索引</h3><p> 由于Hash索引是基于哈希表的，所以时间复杂度是 O（1），在哈希冲突的时候，性能会降低一些。使用哈希索引的话，要尽量的避免哈希冲突 。</p>
<ul>
<li><p>Memory 引擎支持显示 Hash 索引</p>
</li>
<li><p>InnoDB 引擎支持  “自适应Hash索引”，当 InnoDB发现某些索引值使用的非常频繁的时候，会在内存里面基于B+Tree的基础之上创建一个 Hash 索引去提升查询效率，自适应Hash 索引没有办法直接介入，只有一个开关</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">show variables like &#39;innodb_adaptive_hash_index&#39;; </span><br><span class="line">set global innodb_adaptive_hash_index &#x3D; &#39;ON&#39;; </span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="空间索引（R-Tree索引）"><a href="#空间索引（R-Tree索引）" class="headerlink" title="空间索引（R-Tree索引）"></a>空间索引（R-Tree索引）</h3><ul>
<li>存储 GIS 数据，基于R-Tree</li>
<li>MySQL 5.7 开始InnoDB支持空间索引</li>
<li>在GIS领域，做的比较好的是PostgralSQL，不会使用MYQL</li>
</ul>
<h3 id="全文索引"><a href="#全文索引" class="headerlink" title="全文索引"></a>全文索引</h3><h2 id="B-Tree-B-Tree-amp-Hash索引特性与限制"><a href="#B-Tree-B-Tree-amp-Hash索引特性与限制" class="headerlink" title="B-Tree(B+Tree)&amp;Hash索引特性与限制"></a>B-Tree(B+Tree)&amp;Hash索引特性与限制</h2><h3 id="B-Tree（B-Tree）"><a href="#B-Tree（B-Tree）" class="headerlink" title="B-Tree（B+Tree）"></a>B-Tree（B+Tree）</h3><ul>
<li>完全匹配：index(name) =&gt; where name=’name值’</li>
<li>范围匹配：index(age)  =&gt; where age &gt; 5</li>
<li>前缀匹配：index(name) =&gt; where name like ‘张%’</li>
</ul>
<div class="note primary simple"><p>B-Tree索引的限制:</p>
</div>
<ul>
<li>index(name,age,sex)<ul>
<li>查询条件不包含最左列，无法使用索引。<ul>
<li>where age = 5 and sex =1 无法使用索引</li>
</ul>
</li>
<li>跳过了索引中的列，则无法完全使用索引 。<ul>
<li>`where name = ‘王开琦’ and sex = 32 =&gt; 只能使用name这一列</li>
</ul>
</li>
<li>如果查询里面有某个列的范围（模糊）查询，则其右边所有列都无法使用索引<ul>
<li>where name = ‘王开琦’ and age &gt;32 and sex =1 =&gt; 只能使用 name、age 两列 </li>
</ul>
</li>
</ul>
</li>
</ul>
<p>上述的三个限制就是最左前缀原则，最左前缀原则指的是索引按照最左优先的方式匹配索引，不满足以上三个条件的时候都无法完全的使用索引。使用B-Tree索引的时候，索引列的顺序都是非常重要的。以上的三个限制都和索引的顺序有关。在调优的时候，常常也需要根据查询条件去调整索引需要的字段，甚至需要去额外创建一些使用的列相同，但是列顺序不同的索引。</p>
<h3 id="Hash-索引"><a href="#Hash-索引" class="headerlink" title="Hash 索引"></a>Hash 索引</h3><p>一般性能比B-Tree（B+Tree）要好一些，只要哈希不冲突，时间复杂度就是 O(1)</p>
<div class="note primary simple"><p>Hash索引限制:</p>
</div>
<ul>
<li>Hash 索引并不是按照索引值排序，所以没法使用排序</li>
<li>不支持部分索引列匹配查找，这是因为hash索引是用所有列的内容去计算 哈希值的<ul>
<li>hash(a,b) =&gt; where a=1</li>
</ul>
</li>
<li>只支持等值查询（例如 = 、 IN），不支持范围查询（&gt; 、&lt;、 between等 ）、模糊查询 （like）</li>
<li>hash冲突越严重，性能下降越厉害</li>
</ul>
<h2 id="创建索引的原则"><a href="#创建索引的原则" class="headerlink" title="创建索引的原则"></a>创建索引的原则</h2><h3 id="那些场景建议创建索引"><a href="#那些场景建议创建索引" class="headerlink" title="那些场景建议创建索引"></a>那些场景建议创建索引</h3><div class="note primary simple"><p>select语句，频繁作为where条件的字段:</p>
</div>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> employees</span><br><span class="line"><span class="keyword">where</span> first_name = <span class="string">&#x27;Georgi&#x27;</span>;</span><br><span class="line"><span class="comment"># index(first_name)</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> employees</span><br><span class="line"><span class="keyword">where</span> first_name = <span class="string">&#x27;Georgi&#x27;</span></span><br><span class="line">  <span class="keyword">and</span> last_name = <span class="string">&#x27;Gools&#x27;</span>;</span><br><span class="line"><span class="comment"># index(first_name,last_name)</span></span><br><span class="line"><span class="comment"># 在创建联合索引的时候还要考虑最左前缀原则</span></span><br><span class="line"><span class="comment"># index(last_name,first_name)  ====&gt;    where first_name = &#x27;Georgi&#x27;  无法使用该索引</span></span><br></pre></td></tr></table></figure>
<div class="note primary simple"><p>update/delete语句的where条件：</p>
</div>
<p>update/delete 语句需要先根据where条件查询出对应的数据，然后再对这些数据进行更新或者删除，创建索引可以提升查询的效率。</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">update</span> employees</span><br><span class="line"><span class="keyword">set</span> first_name = <span class="string">&#x27;Jim&#x27;</span></span><br><span class="line"><span class="keyword">where</span> emp_no = <span class="string">&#x27;100001&#x27;</span>;</span><br><span class="line"><span class="comment"># 这条语句由于  emp_no 是主键，不需要额外创建索引</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">delete</span></span><br><span class="line"><span class="keyword">from</span> employees</span><br><span class="line"><span class="keyword">where</span> first_name = <span class="string">&#x27;Georgi&#x27;</span>;</span><br></pre></td></tr></table></figure>
<div class="note primary simple"><p>需要分组、排序的字段：</p>
</div>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 查询各个部门下有过多少位员工（忽略start_data和end_date）</span></span><br><span class="line"><span class="keyword">select</span> dept_no, <span class="keyword">count</span>(*)</span><br><span class="line"><span class="keyword">from</span> dept_emp</span><br><span class="line"><span class="keyword">group</span> <span class="keyword">by</span> dept_no;</span><br></pre></td></tr></table></figure>
<div class="note primary simple"><p>distinct所使用的字段</p>
</div>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> <span class="keyword">distinct</span>(first_name)</span><br><span class="line"><span class="keyword">from</span> employees</span><br></pre></td></tr></table></figure>
<div class="note primary simple"><p>字段的值有唯一性约束：</p>
</div>
<p>一些索引本身就可以起到约束的作用，比如说唯一索引、主键索引等等，都是有唯一性约束的。如果表里面有个字段要求它唯一，比如登录的用户名，那么就可以为这个字段创建唯一索引。</p>
<div class="note primary simple"><p>对于多表字段，联接字段应创建索引，<strong>且类型务必保持一致</strong>，避免隐式转换，隐式转换可能导致索引无法使用 </p>
</div>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 查询工号为100001的雇员待过的部门</span></span><br><span class="line"><span class="comment"># 多表关联表 比如下面的dept_emp，要创建联合主键索引 primary key (emp_no, dept_no),</span></span><br><span class="line"><span class="keyword">select</span> emp.*, d.dept_name</span><br><span class="line"><span class="keyword">from</span> employees emp</span><br><span class="line">         <span class="keyword">left</span> <span class="keyword">join</span> dept_emp de</span><br><span class="line">                   <span class="keyword">on</span> emp.emp_no = de.emp_no</span><br><span class="line">         <span class="keyword">left</span> <span class="keyword">join</span> departments d</span><br><span class="line">                   <span class="keyword">on</span> de.dept_no = d.dept_no</span><br><span class="line"><span class="keyword">where</span> emp.emp_no = <span class="string">&#x27;100001&#x27;</span>;</span><br></pre></td></tr></table></figure>
<p>上述SQL的查询计划：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">&quot;query_block&quot;</span>: &#123;</span><br><span class="line">    <span class="attr">&quot;select_id&quot;</span>: <span class="number">1</span>,</span><br><span class="line">    <span class="attr">&quot;cost_info&quot;</span>: &#123;</span><br><span class="line">      <span class="attr">&quot;query_cost&quot;</span>: <span class="string">&quot;1.90&quot;</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">&quot;nested_loop&quot;</span>: [</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;table&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;table_name&quot;</span>: <span class="string">&quot;emp&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;access_type&quot;</span>: <span class="string">&quot;const&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;possible_keys&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;PRIMARY&quot;</span></span><br><span class="line">          ],</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;PRIMARY&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;used_key_parts&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;emp_no&quot;</span></span><br><span class="line">          ],</span><br><span class="line">          <span class="attr">&quot;key_length&quot;</span>: <span class="string">&quot;4&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;ref&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;const&quot;</span></span><br><span class="line">          ],</span><br><span class="line">          <span class="attr">&quot;rows_examined_per_scan&quot;</span>: <span class="number">1</span>,</span><br><span class="line">          <span class="attr">&quot;rows_produced_per_join&quot;</span>: <span class="number">1</span>,</span><br><span class="line">          <span class="attr">&quot;filtered&quot;</span>: <span class="string">&quot;100.00&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;cost_info&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;read_cost&quot;</span>: <span class="string">&quot;0.00&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;eval_cost&quot;</span>: <span class="string">&quot;0.10&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;prefix_cost&quot;</span>: <span class="string">&quot;0.00&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;data_read_per_join&quot;</span>: <span class="string">&quot;136&quot;</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;used_columns&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;emp_no&quot;</span>,</span><br><span class="line">            <span class="string">&quot;birth_date&quot;</span>,</span><br><span class="line">            <span class="string">&quot;first_name&quot;</span>,</span><br><span class="line">            <span class="string">&quot;last_name&quot;</span>,</span><br><span class="line">            <span class="string">&quot;gender&quot;</span>,</span><br><span class="line">            <span class="string">&quot;hire_date&quot;</span></span><br><span class="line">          ]</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;table&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;table_name&quot;</span>: <span class="string">&quot;de&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;access_type&quot;</span>: <span class="string">&quot;ref&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;possible_keys&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;PRIMARY&quot;</span></span><br><span class="line">          ],</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;PRIMARY&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;used_key_parts&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;emp_no&quot;</span></span><br><span class="line">          ],</span><br><span class="line">          <span class="attr">&quot;key_length&quot;</span>: <span class="string">&quot;4&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;ref&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;const&quot;</span></span><br><span class="line">          ],</span><br><span class="line">          <span class="attr">&quot;rows_examined_per_scan&quot;</span>: <span class="number">2</span>,</span><br><span class="line">          <span class="attr">&quot;rows_produced_per_join&quot;</span>: <span class="number">2</span>,</span><br><span class="line">          <span class="attr">&quot;filtered&quot;</span>: <span class="string">&quot;100.00&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;using_index&quot;</span>: <span class="literal">true</span>,</span><br><span class="line">          <span class="attr">&quot;cost_info&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;read_cost&quot;</span>: <span class="string">&quot;1.00&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;eval_cost&quot;</span>: <span class="string">&quot;0.20&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;prefix_cost&quot;</span>: <span class="string">&quot;1.20&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;data_read_per_join&quot;</span>: <span class="string">&quot;64&quot;</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;used_columns&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;emp_no&quot;</span>,</span><br><span class="line">            <span class="string">&quot;dept_no&quot;</span></span><br><span class="line">          ]</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;,</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="attr">&quot;table&quot;</span>: &#123;</span><br><span class="line">          <span class="attr">&quot;table_name&quot;</span>: <span class="string">&quot;d&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;access_type&quot;</span>: <span class="string">&quot;eq_ref&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;possible_keys&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;PRIMARY&quot;</span></span><br><span class="line">          ],</span><br><span class="line">          <span class="attr">&quot;key&quot;</span>: <span class="string">&quot;PRIMARY&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;used_key_parts&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;dept_no&quot;</span></span><br><span class="line">          ],</span><br><span class="line">          <span class="attr">&quot;key_length&quot;</span>: <span class="string">&quot;16&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;ref&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;employees.de.dept_no&quot;</span></span><br><span class="line">          ],</span><br><span class="line">          <span class="attr">&quot;rows_examined_per_scan&quot;</span>: <span class="number">1</span>,</span><br><span class="line">          <span class="attr">&quot;rows_produced_per_join&quot;</span>: <span class="number">2</span>,</span><br><span class="line">          <span class="attr">&quot;filtered&quot;</span>: <span class="string">&quot;100.00&quot;</span>,</span><br><span class="line">          <span class="attr">&quot;cost_info&quot;</span>: &#123;</span><br><span class="line">            <span class="attr">&quot;read_cost&quot;</span>: <span class="string">&quot;0.50&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;eval_cost&quot;</span>: <span class="string">&quot;0.20&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;prefix_cost&quot;</span>: <span class="string">&quot;1.90&quot;</span>,</span><br><span class="line">            <span class="attr">&quot;data_read_per_join&quot;</span>: <span class="string">&quot;368&quot;</span></span><br><span class="line">          &#125;,</span><br><span class="line">          <span class="attr">&quot;used_columns&quot;</span>: [</span><br><span class="line">            <span class="string">&quot;dept_no&quot;</span>,</span><br><span class="line">            <span class="string">&quot;dept_name&quot;</span></span><br><span class="line">          ]</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    ]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="那些场景不建议创建索引"><a href="#那些场景不建议创建索引" class="headerlink" title="那些场景不建议创建索引"></a>那些场景不建议创建索引</h3><ul>
<li><p>where字句里用不到的字段</p>
<p>索引的作用是快速定位到想要的数据，如果查询条件里面用不到，就没有必要为这个字段创建索引了</p>
</li>
<li><p>表的记录非常少，这种情况下，是否创建索引对查询效率的影响并不大</p>
</li>
<li><p>有大量重复数据，选择性低。创建索引的作用是不大的，也不建议创建索引</p>
<p>索引的选择性越高，查询效率越好，因为选择性高的索引在查询的时候可以过滤掉更多的行。这也是唯一索引比普通索引查询效率好的原因。比如性别字段就不能创建索引。</p>
</li>
<li><p>频繁更新的字段，如果创建索引要考虑其索引维护开销</p>
<p>在修改和删除数据的时候需要更新索引</p>
<p>如果某一个字段修改非常的频繁，而查询很少的话，不建议为这个字段创建索引</p>
</li>
</ul>
<h2 id="索引失效与解决方案"><a href="#索引失效与解决方案" class="headerlink" title="索引失效与解决方案"></a>索引失效与解决方案</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  可能导致索引失效的场景：</span></span><br><span class="line"><span class="comment">  1.索引列不独立。独立是指：列不能是表达式的一部分，也不能是函数的参数</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment"># 示例一：索引字段不独立（索引字段进行了表达式计算）  type是all，发生了全表扫描</span></span><br><span class="line"><span class="keyword">explain</span></span><br><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> employees</span><br><span class="line"><span class="keyword">where</span> emp_no + <span class="number">1</span> = <span class="number">10003</span>;</span><br><span class="line"><span class="comment"># 解决方案： 事先计算好表达式的值，再传过来，避免在SQL where条件 = 的左侧做计算</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 示例二：索引字段不独立（索引字段是函数的参数）</span></span><br><span class="line"><span class="keyword">explain</span></span><br><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> employees</span><br><span class="line"><span class="keyword">where</span> <span class="keyword">substring</span>(first_name, <span class="number">1</span>, <span class="number">3</span>) = <span class="string">&#x27;Geo&#x27;</span>;</span><br><span class="line"><span class="comment"># 解决方案：预先计算好结果，再传过来，在 where条件的左侧，不要使用函数；或者使用等价的SQL去实现</span></span><br><span class="line"><span class="keyword">explain</span></span><br><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> employees</span><br><span class="line"><span class="keyword">where</span> first_name <span class="keyword">like</span> <span class="string">&#x27;Geo%&#x27;</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 实例三：使用了左模糊</span></span><br><span class="line"><span class="keyword">explain</span></span><br><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> employees</span><br><span class="line"><span class="keyword">where</span> first_name <span class="keyword">like</span> <span class="string">&#x27;%Geo%&#x27;</span>;</span><br><span class="line"><span class="comment"># 解决方案：尽量避免使用左模糊，如果避免不了，可以考虑使用搜索引擎去解决</span></span><br><span class="line"><span class="keyword">explain</span></span><br><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> employees</span><br><span class="line"><span class="keyword">where</span> first_name <span class="keyword">like</span> <span class="string">&#x27;Geo%&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 实例四：使用OR查询的部分字段没有索引，employee 表的 first_name 有索引，last_name 没有添加索引</span></span><br><span class="line"><span class="comment"># type index_merge 为索引合并；索引和并是 mysql 内部的优化机制，分别对两个索引进行了扫描，最后再把两个结果集进行了合并</span></span><br><span class="line"><span class="comment"># 带来的好处就是避免了全表扫描</span></span><br><span class="line"><span class="keyword">explain</span></span><br><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> employees</span><br><span class="line"><span class="keyword">where</span> first_name = <span class="string">&#x27;Georgi&#x27;</span></span><br><span class="line">   <span class="keyword">or</span> last_name = <span class="string">&#x27;Georgi&#x27;</span>;</span><br><span class="line"><span class="comment"># 解决方案：分别为first_name 以及last_name 字段创建索引</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># 实例五：字符串条件未使用 &#x27;&#x27; 引起来</span></span><br><span class="line"><span class="keyword">explain</span></span><br><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> dept_emp</span><br><span class="line"><span class="keyword">where</span> dept_no = <span class="number">3</span>;</span><br><span class="line"><span class="comment"># 解决方案,规范的使用SQL （type为 ref 是使用了部分索引）</span></span><br><span class="line"><span class="keyword">explain</span></span><br><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> dept_emp</span><br><span class="line"><span class="keyword">where</span> dept_no = <span class="string">&#x27;3&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment"># 实例六：不符合最左前缀原则的查询</span></span><br><span class="line"><span class="comment"># 存在index（last_name,first_name）</span></span><br><span class="line"><span class="keyword">explain</span></span><br><span class="line"><span class="keyword">select</span> *</span><br><span class="line"><span class="keyword">from</span> employees</span><br><span class="line"><span class="keyword">where</span> first_name = <span class="string">&#x27;Facello&#x27;</span>;</span><br><span class="line"><span class="comment"># 解决方案，调整索引顺序，变成 index(first_name,last_name)</span></span><br><span class="line"><span class="comment"># j</span></span><br></pre></td></tr></table></figure>
</article><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="/media/top_img.jpg" data-sites="wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/media/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">王开琦</div><div class="author-info__description">今日事今日毕</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">15</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">17</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B4%A2%E5%BC%95%E7%9A%84%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84"><span class="toc-number">1.</span> <span class="toc-text">索引的数据结构</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#B-Tree"><span class="toc-number">1.1.</span> <span class="toc-text">B-Tree</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Hash%E7%B4%A2%E5%BC%95"><span class="toc-number">1.2.</span> <span class="toc-text">Hash索引</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%A9%BA%E9%97%B4%E7%B4%A2%E5%BC%95%EF%BC%88R-Tree%E7%B4%A2%E5%BC%95%EF%BC%89"><span class="toc-number">1.3.</span> <span class="toc-text">空间索引（R-Tree索引）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%A8%E6%96%87%E7%B4%A2%E5%BC%95"><span class="toc-number">1.4.</span> <span class="toc-text">全文索引</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#B-Tree-B-Tree-amp-Hash%E7%B4%A2%E5%BC%95%E7%89%B9%E6%80%A7%E4%B8%8E%E9%99%90%E5%88%B6"><span class="toc-number">2.</span> <span class="toc-text">B-Tree(B+Tree)&amp;Hash索引特性与限制</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#B-Tree%EF%BC%88B-Tree%EF%BC%89"><span class="toc-number">2.1.</span> <span class="toc-text">B-Tree（B+Tree）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Hash-%E7%B4%A2%E5%BC%95"><span class="toc-number">2.2.</span> <span class="toc-text">Hash 索引</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E7%B4%A2%E5%BC%95%E7%9A%84%E5%8E%9F%E5%88%99"><span class="toc-number">3.</span> <span class="toc-text">创建索引的原则</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%82%A3%E4%BA%9B%E5%9C%BA%E6%99%AF%E5%BB%BA%E8%AE%AE%E5%88%9B%E5%BB%BA%E7%B4%A2%E5%BC%95"><span class="toc-number">3.1.</span> <span class="toc-text">那些场景建议创建索引</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%82%A3%E4%BA%9B%E5%9C%BA%E6%99%AF%E4%B8%8D%E5%BB%BA%E8%AE%AE%E5%88%9B%E5%BB%BA%E7%B4%A2%E5%BC%95"><span class="toc-number">3.2.</span> <span class="toc-text">那些场景不建议创建索引</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B4%A2%E5%BC%95%E5%A4%B1%E6%95%88%E4%B8%8E%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-number">4.</span> <span class="toc-text">索引失效与解决方案</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E7%89%B9%E5%AE%9A%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%8E%9F%E7%90%86%E5%92%8C%E8%B0%83%E4%BC%98/" title="3.数据库-数据库监控与调优-特定语句的原理和调优"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="3.数据库-数据库监控与调优-特定语句的原理和调优"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E7%89%B9%E5%AE%9A%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%8E%9F%E7%90%86%E5%92%8C%E8%B0%83%E4%BC%98/" title="3.数据库-数据库监控与调优-特定语句的原理和调优">3.数据库-数据库监控与调优-特定语句的原理和调优</a><time datetime="2022-04-22T08:14:26.000Z" title="发表于 2022-04-22 16:14:26">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="数据库调优理论"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="数据库调优理论"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%95%B0%E6%8D%AE%E5%BA%93%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="数据库调优理论">数据库调优理论</a><time datetime="2022-04-22T08:13:31.000Z" title="发表于 2022-04-22 16:13:31">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%85%A2%E6%9F%A5%E8%AF%A2%E5%8F%91%E7%8E%B0%E4%B8%8E%E5%88%86%E6%9E%90/" title="慢查询发现与分析"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="慢查询发现与分析"/></a><div class="content"><a class="title" href="/blog/3-%E6%95%B0%E6%8D%AE%E5%BA%93-%E6%95%B0%E6%8D%AE%E5%BA%93%E7%9B%91%E6%8E%A7%E4%B8%8E%E8%B0%83%E4%BC%98-%E6%85%A2%E6%9F%A5%E8%AF%A2%E5%8F%91%E7%8E%B0%E4%B8%8E%E5%88%86%E6%9E%90/" title="慢查询发现与分析">慢查询发现与分析</a><time datetime="2022-04-22T08:12:32.000Z" title="发表于 2022-04-22 16:12:32">2022-04-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/1-Java-JVM%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="JVM 调优理论"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JVM 调优理论"/></a><div class="content"><a class="title" href="/blog/1-Java-JVM%E8%B0%83%E4%BC%98%E7%90%86%E8%AE%BA/" title="JVM 调优理论">JVM 调优理论</a><time datetime="2022-04-21T06:40:41.000Z" title="发表于 2022-04-21 14:40:41">2022-04-21</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/20-%E5%BE%AE%E6%9C%8D%E5%8A%A1%E6%9E%B6%E6%9E%84-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86Eureka/" title="服务治理Eureka"><img src= "" data-lazy-src="/media/top_img.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="服务治理Eureka"/></a><div class="content"><a class="title" href="/blog/20-%E5%BE%AE%E6%9C%8D%E5%8A%A1%E6%9E%B6%E6%9E%84-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86-%E6%9C%8D%E5%8A%A1%E6%B2%BB%E7%90%86Eureka/" title="服务治理Eureka">服务治理Eureka</a><time datetime="2022-04-13T13:18:27.000Z" title="发表于 2022-04-13 21:18:27">2022-04-13</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="footer_custom_text">Copyright© 2022 blog.wkq.pub <span>陇ICP备2021003596号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      true && mermaid.init()
    })
  }
}</script></div><div class="aplayer no-destroy" data-id="7675104902" data-server="tencent" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div><canvas class="fireworks" mobile="true"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script></div><script src="/live2d_models/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2d_models/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2d_models/assets/penchan.model.json"},"display":{"position":"left","width":100,"height":150,"hOffset":-10,"vOffset":40},"mobile":{"show":true},"react":{"opacity":0.7},"log":false});</script></body></html>